import './imports'
import Header from '../components/Header';
import NewsList from '../components/NewsList';
import { getItemNode } from '../libs/utils';
import NoCollectTip from '../components/NoCollectTip'
((doc) => {
    const oApp = doc.querySelector('#app')
    const followedList = JSON.parse(localStorage.getItem('followedList') || '[]');
    let oNewsListWrapper = null;
    const init = () => {
        render();
        oNewsListWrapper && bindEvent();
    }
    function render() {
        const headerTpl = Header.tpl({
            url: '/',
            title: '我的新闻',
            showLeftIcon: true,
            showRightIcon: false
        });
        if (followedList.length) {
            const listWrapperTpl = NewsList.wrapperTpl(44);
            oApp.innerHTML += (headerTpl + listWrapperTpl);
            oNewsListWrapper = oApp.querySelector('.news-list');
            renderList(followedList);
        } else {
            oApp.innerHTML += (headerTpl + NoCollectTip.tpl());
        }
        oNewsListWrapper = oApp.querySelector('.news-list')
    }
    function bindEvent() {
        oNewsListWrapper.addEventListener('click', goToDetail, false);
    }
    function renderList(data) {
        const newsListTpl = NewsList.tpl({
            data,
            pageNum: -1
        });
        oNewsListWrapper.innerHTML += newsListTpl;
    }
    //提取选中项数据并保存到localstorage中
    function setCurrentNew(options) {
        const { idx } = options;
        const currentNew = followedList[idx];
        localStorage.setItem('currentNew', JSON.stringify(currentNew))
    }
    function goToDetail(ev) {
        /* 
        要找到对应的新闻，需根据item标签中的pageNum和index这两个数据去列表中找，
        const oItem = arguments[1].target;
        但是这里拿到的oItem并不能确保是想要的item标签项
        因为有可能点的是author或者title等标签。这时候要写个函数getItemNode处理下，确保拿到的是news-item标签
        */
        const oItem = getItemNode(ev.target);
        const options = {
            idx: oItem.dataset.index,
            pageNum: oItem.dataset.page
        }
        setCurrentNew(options);
        window.location.href = `detail.html?path=${location.pathname}`;
    }
    init();
})(document);